package com.df.tv.launcher.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.text.TextUtils;

import com.df.tv.launcher.exception.FileAccessException;
import com.telecom.tv189.comlib.util.Log;

public class FileAccess implements Serializable {
    private static final long serialVersionUID = 1L;
    private RandomAccessFile oSavedFile;

    public FileAccess() throws Exception {
        this("", 0);
    }

    public FileAccess(String sName, long nPos) throws FileAccessException, IOException {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == false) { throw new FileAccessException(
                FileAccessException.EXTERNAL_STORAGE_DEVICE_NOT_FOUND); }
        oSavedFile = new RandomAccessFile(sName, "rw");
        oSavedFile.seek(nPos);
    }

    public synchronized void setFileSize(long size) throws IOException {
        oSavedFile.setLength(size);

    }

    public synchronized int write(byte[] b, int nStart, int nLen) throws IOException {
        int n = 0;
        oSavedFile.write(b, nStart, nLen);
        n = nLen;
        return n;
    }

    public long getFileLength() throws IOException {
        return oSavedFile.length();
    }

    public void close() throws IOException {
        Log.d("file closing");
        oSavedFile.close();

    }

    /**
     * save the data to local file /data/data/xxx.xx.xx/file/
     * 
     * @param context
     * @param fileName
     * @param data
     * @return true save success,false fail
     */
    public static boolean writeDataToFile(Context context, String fileName, String data) {
        if (!TextUtils.isEmpty(data) && !TextUtils.isEmpty(fileName)) {
            FileOutputStream fos;
            try {
                fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
                fos.write(data.getBytes());
                fos.close();
                return true;
            } catch (FileNotFoundException e) {
                Log.d(e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d(e.getLocalizedMessage());
            }
        }
        return false;
    }

    /**
     * get the data from local file /data/data/xxx.xx.xx/file/
     * 
     * @param ctx
     * @param fileName
     * @return String
     */
    public static String getFileData(Context ctx, String fileName) {
        byte[] b = new byte[1024];
        StringBuffer sb = new StringBuffer();
        FileInputStream fis = null;
        try {
            fis = ctx.openFileInput(fileName);
            int num;
            while ((num = fis.read(b)) != -1) {
                sb.append(new String(b, 0, num));
            }
        } catch (FileNotFoundException e) {
            Log.d(e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d(e.getLocalizedMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {}
            }
        }
        return sb.toString();
    }

    public static String getTestDataFromAssets(Context context, String filename) {
        String data = "";
        try {
            AssetManager am = context.getAssets();
            InputStream is = am.open(filename);
            if (is != null) {
                byte[] info = readInputStream(is);
                data = new String(info);
                // ULog.v(TAG, "getTestDataFromAssets data = " + data);
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}
